package view.impl;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import cqut.edu.cn.temp_20160410.R;

/**
 * 带删除键的EditText
 */
public class ClearEditText extends EditText {
	private static final int ICON_CLEAR_DEFAULT = R.drawable.icon_clear;

	private Drawable drawableClear;

	public ClearEditText(Context context) {
		super(context);
		init(context, null);
	}

	public ClearEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.ClearEditText);
		int iconClear = typedArray.getResourceId(
				R.styleable.ClearEditText_iconClear, ICON_CLEAR_DEFAULT);
		drawableClear = getResources().getDrawable(iconClear);
		updateIconClear();
		typedArray.recycle();

		addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				updateIconClear();
			}
		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			int xDown = (int) event.getX();

			if (xDown >= (getWidth() - getCompoundPaddingRight())
					&& xDown < getWidth()) {
				setText("");
			}
		}
		return super.onTouchEvent(event);
	}

	public void updateIconClear() {

		Drawable[] drawables = getCompoundDrawables();
		if (length() > 0 && isFocused()== true) {
			setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1],
					drawableClear, drawables[3]);
		} else if(isFocused() == false) {
			setCompoundDrawablesWithIntrinsicBounds(null, null,
					null, null);
		}
	}

	public void setIconClear(int resId) {
		drawableClear = getResources().getDrawable(resId);
		updateIconClear();
	}
}
